package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"net/http"
	"os"
	"os/signal"
	"syscall"

	"golang.org/x/sync/errgroup"
)

var HttpServers []*http.Server

var monitoredSignals = []os.Signal{
	syscall.SIGHUP,
	syscall.SIGINT,
	syscall.SIGTERM,
	syscall.SIGQUIT,
}

func main() {
	g, gctx := errgroup.WithContext(context.Background())
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, monitoredSignals...)

	helloHandler := http.NewServeMux()
	httpSrv1 := &http.Server{Addr: ":19991", Handler: helloHandler}
	httpSrv2 := &http.Server{Addr: ":19992", Handler: helloHandler}
	HttpServers = append(HttpServers, httpSrv1, httpSrv2)
	for _, s := range HttpServers {
		s := s
		g.Go(func() error {
			return s.ListenAndServe()
		})
		g.Go(func() error {
			<-gctx.Done()
			return s.Shutdown(context.Background())
		})
	}
	g.Go(func() error {
		select {
		case <-gctx.Done():
			return gctx.Err()
		case <-quit:
			return errors.New("quit gracefully")
		}
	})

	if err := g.Wait(); err != nil {
		fmt.Println(err)
	}
}

type hello struct {
}

func (h hello) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, "hello, world!\n")
}
